import {
  Tenant,
  TenantFilter,
  CreateTenantRequest,
  UpdateTenantRequest,
  TenantStats,
  SubscriptionPlan,
  PaginatedResponse,
  ApiResponse,
} from '@/types';

// 租户服务类
class TenantService {
  private baseUrl = '/api/tenants';

  // 获取租户列表
  async getTenants(params: TenantFilter & { page?: number; pageSize?: number } = {}): Promise<PaginatedResponse<Tenant>> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    const response = await fetch(`${this.baseUrl}?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch tenants: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取单个租户详情
  async getTenant(id: string): Promise<ApiResponse<Tenant>> {
    const response = await fetch(`${this.baseUrl}/${id}`);
    if (!response.ok) {
      throw new Error(`Failed to fetch tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 创建租户
  async createTenant(data: CreateTenantRequest): Promise<ApiResponse<Tenant>> {
    const response = await fetch(this.baseUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to create tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 更新租户
  async updateTenant(id: string, data: UpdateTenantRequest): Promise<ApiResponse<Tenant>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to update tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 删除租户
  async deleteTenant(id: string): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/${id}`, {
      method: 'DELETE',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to delete tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 批量删除租户
  async batchDeleteTenants(ids: string[]): Promise<ApiResponse<void>> {
    const response = await fetch(`${this.baseUrl}/batch`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ids }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to batch delete tenants: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取租户统计信息
  async getTenantStats(id: string): Promise<ApiResponse<TenantStats>> {
    const response = await fetch(`${this.baseUrl}/${id}/stats`);
    if (!response.ok) {
      throw new Error(`Failed to fetch tenant stats: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取所有租户统计信息
  async getAllTenantStats(): Promise<ApiResponse<TenantStats[]>> {
    const response = await fetch(`${this.baseUrl}/stats`);
    if (!response.ok) {
      throw new Error(`Failed to fetch all tenant stats: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 获取订阅套餐列表
  async getSubscriptionPlans(): Promise<ApiResponse<SubscriptionPlan[]>> {
    const response = await fetch('/api/subscription-plans');
    if (!response.ok) {
      throw new Error(`Failed to fetch subscription plans: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 更新租户订阅套餐
  async updateTenantSubscription(
    tenantId: string, 
    subscriptionPlanId: string
  ): Promise<ApiResponse<Tenant>> {
    const response = await fetch(`${this.baseUrl}/${tenantId}/subscription`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ subscriptionPlanId }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to update tenant subscription: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 暂停租户
  async suspendTenant(id: string, reason?: string): Promise<ApiResponse<Tenant>> {
    const response = await fetch(`${this.baseUrl}/${id}/suspend`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ reason }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to suspend tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 恢复租户
  async resumeTenant(id: string): Promise<ApiResponse<Tenant>> {
    const response = await fetch(`${this.baseUrl}/${id}/resume`, {
      method: 'POST',
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to resume tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 续费租户
  async renewTenant(id: string, months: number): Promise<ApiResponse<Tenant>> {
    const response = await fetch(`${this.baseUrl}/${id}/renew`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ months }),
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to renew tenant: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 导出租户数据
  async exportTenants(params: TenantFilter = {}): Promise<Blob> {
    const searchParams = new URLSearchParams();
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        searchParams.append(key, String(value));
      }
    });

    const response = await fetch(`${this.baseUrl}/export?${searchParams.toString()}`);
    if (!response.ok) {
      throw new Error(`Failed to export tenants: ${response.statusText}`);
    }
    
    return response.blob();
  }

  // 导入租户数据
  async importTenants(file: File): Promise<ApiResponse<{ success: number; failed: number; errors: string[] }>> {
    const formData = new FormData();
    formData.append('file', file);

    const response = await fetch(`${this.baseUrl}/import`, {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `Failed to import tenants: ${response.statusText}`);
    }
    
    return response.json();
  }
}

// 导出单例实例
export const tenantService = new TenantService();
export default tenantService;